package com.jieshuibao.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jieshuibao.common.config.Global;
import com.jieshuibao.common.utils.Md5Util;
import com.jieshuibao.model.db.CmsArticle;
import com.jieshuibao.model.db.CmsArticleExample;
import com.jieshuibao.model.db.CmsCategory;
import com.jieshuibao.model.db.User;
import com.jieshuibao.model.domain.AddArticleReq;
import com.jieshuibao.model.domain.AddArticleRes;
import com.jieshuibao.model.domain.ArticleCategory;
import com.jieshuibao.model.domain.ArticleCategoryResponse;
import com.jieshuibao.model.domain.ArticleLoginReq;
import com.jieshuibao.model.domain.ArticleLoginRes;
import com.jieshuibao.model.domain.ArticleRes;
import com.jieshuibao.model.domain.ArticlesReq;
import com.jieshuibao.model.domain.ArticlesRes;
import com.jieshuibao.model.domain.CookieUser;
import com.jieshuibao.model.domain.DelArticleReq;
import com.jieshuibao.service.ArticelService;
import com.jieshuibao.service.CmsArticleService;
import com.jieshuibao.service.RedisService;
import com.jieshuibao.service.UserService;
import com.jieshuibao.util.CookieGenerator;
import com.jieshuibao.util.StringUtils;
import com.jieshuibao.util.UUIDGenerator;

@Controller
@RequestMapping("article")
public class ArticleLoginController {

	private static Logger alogger = Logger
			.getLogger(ArticleLoginController.class);

	@Resource
	private UserService userService;
	@Resource
	private CmsArticleService cmsArticleService;
	@Resource
	private RedisService redisService;
	@Resource
	private ArticelService articelService;
	
	@RequestMapping("/tologin")
	@ResponseBody
	public Object tologin(){
		String randomKey = "randomCode"+System.currentTimeMillis();
		Map<String,String> map = new HashMap<String,String>();
		map.put("code", Global.SUCCESS);
		map.put("randomCodeKey", randomKey);
		return map;
	}
	/**
	 * 用户登录验证
	 * 
	 * @param model
	 * @param account
	 * @param pwd
	 * @param request
	 * @return status
	 * @throws IOException
	 */
	@RequestMapping("/login")
	@ResponseBody
	public Object login(Model model, @RequestBody ArticleLoginReq req,
			String remember, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		ArticleLoginRes res = new ArticleLoginRes();
		String account = req.getAccount();
		String pwd = req.getPwd();
		String randomCode = req.getRandomCode();
		String randomCodeKey = req.getRandomCodeKey();
		if(StringUtils.isEmpty(randomCode)){
			res.setCode(Global.FAIL);
			res.setDes("验证码为空");
			return res;
		}
//		String code = (String) session.getAttribute("randCode");
		if(StringUtils.isEmpty(randomCodeKey)){
			res.setCode(Global.FAIL);
			res.setDes("系统繁忙");
			return res;
		}
		String code = redisService.get(randomCodeKey);
		alogger.warn("redis获取到的验证码为：randomCodeKey---"+randomCodeKey+",code"+code+",接收到的验证码为:"+randomCode);
		if(!randomCode.equals(code)){
			res.setCode(Global.FAIL);
			res.setDes("验证码超时或错误");
			return res;
		}
//		session.removeAttribute("randomCode");
		redisService.delete(randomCodeKey);
		if (null != account && null != pwd && !"".equals(account)
				&& !"".equals(pwd)) {
			User userByphone = userService.getUserByphone(account);
			if (userByphone!=null) {
				Integer role = userByphone.getRole();
				if (role==0) {
					res.setCode(Global.FAIL);
					res.setDes("账号异常，请联系管理员");
					return res;
				}
				
				if(role!=2){
					res.setCode(Global.FAIL);
					res.setDes("只有咨询师可以登录！");
					return res;
				}
				
				if (userByphone.getPwd().equals(Md5Util.Md5(pwd))
						|| Md5Util.Md5(userByphone.getPwd()).equals(Md5Util.Md5(pwd))) {
//					session.setAttribute("ArticleloginUser", admin);
					//String cookieId = "cookid"+System.currentTimeMillis()+"_"+account;
					String pcCookie = CookieGenerator.pcCookie(userByphone.getPhoneNumber());
					
					CookieUser cookieUser = new CookieUser();
					cookieUser.setPhoneNumber(userByphone.getPhoneNumber());
					cookieUser.setPhone(userByphone.getPhone());
					
					redisService.setObject(pcCookie, cookieUser,600);
					res.setCode(Global.SUCCESS);
					res.setCookieId(pcCookie);
					res.setName(userByphone.getRealName());
					String headImage = userByphone.getHeadImage();
					if(StringUtils.isNotEmpty(headImage)){
						res.setHeadImg(Global.getConfig("server.url")+"/showImg"+Global.getConfig("head.images.path")+headImage);
					}
					res.setDes("登录成功");
					return res;
				} else {// 密码错误

				}

			} else {// 用户名为不存在 或者数量大于1

			}
		} else {// 密码为空

		}

		res.setCode(Global.FAIL);
		res.setDes("用户名或密码错误");
		return res;
	}
	/**
	 * 退出登录
	 * @param request
	 * @return
	 */
	@RequestMapping("/logout")
	@ResponseBody
	public Object logout(HttpServletRequest request){
		String cookieId = request.getHeader("cookieId");
		redisService.delete(cookieId);
		Map<String,String> map = new HashMap<String, String>();
		map.put("code", Global.SUCCESS);
		map.put("des", "退出登录");
		return map;
	}
	
	 public Color getRandColor(int fc, int bc) {
	        Random rand = new Random();
	        if (fc > 255) {
	            fc = 255;
	        }
	        if (bc > 255) {
	            bc = 255;
	        }
	        int r = fc + rand.nextInt(bc - fc);
	        int g = fc + rand.nextInt(bc - fc);
	        int b = fc + rand.nextInt(bc - fc);
	        return new Color(r, g, b);
	    }
	 	/**
	 	 * 验证码
	 	 * @param request
	 	 * @param response
	 	 * @throws ServletException
	 	 * @throws IOException
	 	 */
	    @RequestMapping("/randCode/{randomCodeKey}")
	    public void randCode(HttpServletRequest request,@PathVariable String randomCodeKey, HttpServletResponse response) throws ServletException, IOException {
	        // 首先设置页面不缓存
	        response.setHeader("Pragma", "No-cache");
	        response.setHeader("Cache-Control", "no-cache");
	        response.setDateHeader("Expires", 0);

	        // 定义图片的宽度和高度
	        int width = 90, height = 40;
	        // 创建一个图像对象
	        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
	        // 得到图像的环境对象
	        Graphics g = image.createGraphics();

	        Random random = new Random();
	        // 用随机颜色填充图像背景
	        g.setColor(getRandColor(180, 250));
	        g.fillRect(0, 0, width, height);
	        for (int i = 0; i < 5; i++) {
	            g.setColor(getRandColor(50, 100));
	            int x = random.nextInt(width);
	            int y = random.nextInt(height);
	            g.drawOval(x, y, 4, 4);
	        }
	        // 设置字体，下面准备画随机数
	        g.setFont(new Font("", Font.PLAIN, 40));
	        // 随机数字符串
	        String sRand = "";
	        for (int i = 0; i < 4; i++) {
	            // 生成四个数字字符
	            String rand = String.valueOf(random.nextInt(10));
	            sRand += rand;
	            // 生成随机颜色
	            g.setColor(new Color(20 + random.nextInt(80), 20 + random.nextInt(100), 20 + random.nextInt(90)));
	            // 将随机数字画在图像上
	            g.drawString(rand, (17 + random.nextInt(3)) * i + 8, 34);

	            // 生成干扰线
	            for (int k = 0; k < 12; k++) {
	                int x = random.nextInt(width);
	                int y = random.nextInt(height);
	                int xl = random.nextInt(9);
	                int yl = random.nextInt(9);
	                g.drawLine(x, y, x + xl, y + yl);
	            }
	        }

	        // 将生成的随机数字字符串写入Session
//	        request.getSession().setAttribute("randCode", sRand);
	        redisService.set(randomCodeKey, sRand, 300);
	        alogger.warn("生成的验证码为："+sRand);
	        // 使图像生效
	        g.dispose();
	        // 输出图像到页面
	        ImageIO.write(image, "JPEG", response.getOutputStream());
	    }
	/**
	 * 文章列表
	 * @param request
	 * @param req
	 * @return
	 */
	@RequestMapping("/articles")
	@ResponseBody
	public Object articles(HttpServletRequest request,@RequestBody ArticlesReq req) {
		
		CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
		
		
		//String cookieId = request.getHeader("cookieId");
		ArticlesRes res = new ArticlesRes();
		int pageIndex = req.getPageIndex();
		int pageSize = req.getPageSize()==0?10:req.getPageSize();
		int count;
		List<CmsArticle> pageCmsArticle;
		try {
//			User user = (User) request.getSession().getAttribute("ArticleloginUser");
		
			String phoneNumber = cookieUser.getPhoneNumber();
			CmsArticleExample cmsArticleExample = new CmsArticleExample();
			com.jieshuibao.model.db.CmsArticleExample.Criteria createCriteria2 = cmsArticleExample
					.createCriteria();
			createCriteria2.andCreatByEqualTo(phoneNumber);
			createCriteria2.andDelFlagEqualTo(Global.SHOW);
			cmsArticleExample.setPageIndex(pageIndex);
			cmsArticleExample.setPageSize(pageSize);
			cmsArticleExample.setOrderByClause("createDate DESC");
			count = cmsArticleService.countCmsArticle(cmsArticleExample);
			pageCmsArticle = cmsArticleService
					.getPageCmsArticle(cmsArticleExample);
			for (CmsArticle cmsArticle : pageCmsArticle) {
				String categoryId = cmsArticle.getCategoryId();
				CmsCategory categoryById = cmsArticleService.getCmsCategoryById(categoryId);
				if(null != categoryById){
					String name = categoryById.getName();
					cmsArticle.setCategoryId(name);
				}
			}
			res.setCode(Global.SUCCESS);
			res.setDes("请求成功");
			res.setCount(count);
			res.setArticleList(pageCmsArticle);
			return res;
		} catch (Exception e) {
			alogger.error(e.toString());
			e.printStackTrace();
			res.setCode(Global.FAIL);
			res.setDes("系统繁忙");
			return res;
		}
	}
	/**
	 * 添加文章
	 * @param request
	 * @param req
	 * @return
	 */
	@RequestMapping("/addarticle")
	@ResponseBody
	public Object addarticle(HttpServletRequest request,@RequestBody AddArticleReq req){
		//String cookieId = request.getHeader("cookieId");
		AddArticleRes res = new AddArticleRes();
		CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
//		User user = (User) request.getSession().getAttribute("ArticleloginUser");
	/*	User user = redisService.getObejct(cookieId, User.class);
		if(null == user){
			res.setCode(Global.NOTLOGIN);
			res.setDes("用户未登录");
			return res;
		}*/
		try {
			Integer role = cookieUser.getRole();
			if (role!=2) {
				res.setCode(Global.NOTLOGIN);
				res.setDes("只有咨询师可以发布");
				return res;
			}
			
			
			String phoneNumber = cookieUser.getPhoneNumber();
			String categoryId = req.getCategoryId();
			if(StringUtils.isEmpty(categoryId)){
				res.setCode(Global.FAIL);
				res.setDes("文章标签为空");
				return res;
			}
			String content = req.getContent();
			if(StringUtils.isEmpty(content)){
				res.setCode(Global.FAIL);
				res.setDes("文章内容为空");
				return res;
			}
			String title = req.getTitle();
			if(StringUtils.isEmpty(content)){
				res.setCode(Global.FAIL);
				res.setDes("文章标题为空");
				return res;
			}
			CmsArticle article = new CmsArticle();
			article.setId(UUIDGenerator.getUUID());
			article.setTitle(title);
			article.setDescription(content);
			article.setCategoryId(categoryId);
			article.setCreateDate(new Date());
			article.setCreatBy(phoneNumber);
			cmsArticleService.addCmsArticle(article);
			res.setCode(Global.SUCCESS);
			res.setDes("发布成功");
			return res;
		} catch (Exception e) {
			e.printStackTrace();
			alogger.error("用户PC发文章错误："+e.toString());
			res.setCode(Global.FAIL);
			res.setDes("系统繁忙");
			return res;
		}
		
	}
	/**
	 * 删除文章
	 * @param request
	 * @param req
	 * @return
	 */
	@RequestMapping("/delarticle")
	@ResponseBody
	public Object delarticle(HttpServletRequest request,@RequestBody DelArticleReq req){
		//String cookieId = request.getHeader("cookieId");
		String id = req.getId();
		AddArticleRes res = new AddArticleRes();
		CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");

	/*	User user = redisService.getObejct(cookieId, User.class);
		if(null == user){
			res.setCode(Global.NOTLOGIN);
			res.setDes("用户未登录");
			return res;
		}*/
		
		CmsArticle cmsArticleById = cmsArticleService.getCmsArticleById(id);
		if(null != cmsArticleById){
			try {
				String phoneNumber = cookieUser.getPhoneNumber();
				String creatBy = cmsArticleById.getCreatBy();
				if (phoneNumber.equals(creatBy)) {
					cmsArticleById.setDelFlag(Global.HIDE);
					cmsArticleService.updateCmsArticle(cmsArticleById);
					res.setCode(Global.SUCCESS);
					res.setDes("删除成功");
				}else {
					res.setCode(Global.FAIL);
					res.setDes("删除失败");
				}
				return res;
			} catch (Exception e) {
				e.printStackTrace();
				alogger.error("用户PC删除文章错误："+e.toString());
				res.setCode(Global.FAIL);
				res.setDes("系统繁忙");
				return res;
			}
			
		}
		res.setCode(Global.FAIL);
		res.setDes("系统繁忙");
		return res;
	}
	/**
	 * 标签列表
	 * @param request
	 * @return
	 */
	@RequestMapping("/articleCategory")
	@ResponseBody
	public Object articleCategory(HttpServletRequest request){
		ArticleCategoryResponse articleCategoryResponse = new ArticleCategoryResponse();
		/*String cookieId = request.getHeader("cookieId");
		User user = redisService.getObejct(cookieId, User.class);
		if(null == user){
			articleCategoryResponse.setCode(Global.NOTLOGIN);
			articleCategoryResponse.setDes("用户未登录");
			return articleCategoryResponse;
		}*/
		List<ArticleCategory> articleCategory = articelService
				.getArticleCategory("1");
		articleCategoryResponse.setCode(Global.SUCCESS);
		articleCategoryResponse.setDes("请求成功");
		articleCategoryResponse.setCategories(articleCategory);
		return articleCategoryResponse;
	}
	
	@RequestMapping("/article/{id}")
	@ResponseBody
	public Object article(HttpServletRequest request,@PathVariable String id){
		ArticleRes res = new ArticleRes();
	/*	String cookieId = request.getHeader("cookieId");
		User user = redisService.getObejct(cookieId, User.class);
		if(null == user){
			res.setCode(Global.NOTLOGIN);
			res.setDes("用户未登录");
			return res;
		}*/
		CmsArticle cmsArticleById = cmsArticleService.getCmsArticleById(id);
		if(null == cmsArticleById){
			res.setCode(Global.FAIL);
			res.setDes("系统繁忙");
			return res;
		}
		String categoryId = cmsArticleById.getCategoryId();
		CmsCategory cmsCategoryById = cmsArticleService.getCmsCategoryById(categoryId);
		String name = cmsCategoryById.getName();
		cmsArticleById.setCategoryId(name);;
		res.setCode(Global.SUCCESS);
		res.setDes("请求成功");
		res.setArticle(cmsArticleById);
		return res;
	}
}
